#pragma once
#include"data.hpp"
//#include<windows.h>
#include"httplib.h"
namespace cloud {
#define SERVER_ADDR "47.121.24.16"
#define SERVER_PORT 8080
	class Backup {
	private:
		std::string _back_dir;
		DataManager* _data;
	public:
		Backup(const std::string& back_dir, const std::string& back_file)
			:_back_dir(back_dir)
		{
			_data = new DataManager(back_file);



		}
		std::string GetFileIdentifier(const std::string& filename) {
			FileUtil fu(filename);
			std::stringstream ss;
			ss << fu.FileName() << "-" << fu.FileSize() << fu.LastMTime();
			return ss.str();

		}
		bool Runmodule() {
			while (1)
			{
				FileUtil fu(_back_dir);
				std::vector<std::string>array;
				fu.ScanDirectory(&array);
				for (auto& a : array)
				{
					if (IsneedUpload(a) == false) {
						continue;
					}
					if (Upload(a) == true) {
						_data->Insert(a, GetFileIdentifier(a));
						std::cout << "insert susess" << std::endl;
					}
					else { std::cout << "error" << std::endl; }
				   
					std::string id = GetFileIdentifier(a);
					_data->Insert(a, id);
				
				}
				Sleep(1);
			}




		}
		bool IsneedUpload(const std::string& filename)
		{
			std::string id;
			if (_data->GetOneByKey(filename, &id) != false)
			{
				std::string new_id = GetFileIdentifier(filename);
				if (new_id == id) {
					return false;
				
				
				
				}


			}
			/*FileUtil fu(filename);
			if (time(nullptr) - fu.LastMTime() < 3) {
				return false;
			
			}*/
		
			return true;
		
		
		
		}
		bool Upload(const std::string& filename)
		{
			FileUtil fu(filename);
			std::string body;
			fu.GetContent(&body);
			httplib::Client client(SERVER_ADDR, SERVER_PORT);
			httplib::MultipartFormData item;
			item.content = body;
			item.filename = fu.FileName();
			item.name = "file";
		     item.content_type = "application/octet-stream";
			httplib::MultipartFormDataItems items;
			items.push_back(item);
			auto res = client.Post("/upload", items);
			if (!res || res->status != 200)
			{    
				std::cout << res->status << std::endl;
				return false;
			}
			return true;
		}


	};


}
